import os
import ssl
import sys
import urllib

from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from pytube import YouTube

from UI.youtube.main import Ui_Form


class YouTuBeMainWindow(QMainWindow, Ui_Form):
    def __init__(self):
        super().__init__()
        super(Ui_Form, self).__init__()
        self.setupUi(self)

        self.setWindowTitle('YouTube Downloader')
        workdir = os.path.dirname(os.path.abspath(sys.argv[0]))
        self.down_dir_Edit.setText(os.path.join(workdir, "Download"))
        self.down_dir_Button.clicked.connect(self.downPath)
        self.down_Button.clicked.connect(self.download_video)
        self.progress_bar.setValue(0)

    def downPath(self):
        path = QFileDialog.getExistingDirectory(self, "选择文件夹", os.getcwd())
        self.down_dir_Edit.setText(path)

    def download_video(self):
        video_url = self.url_Edit.text()
        print(f"输入下载链接：{video_url}")

        # 设置代理
        proxy_host = "127.0.0.1"
        proxy_port = "7890"
        # 创建一个不验证SSL证书的上下文对象
        context = ssl._create_unverified_context()
        # 创建一个HTTPS处理程序，使用自定义上下文对象
        https_handler = urllib.request.HTTPSHandler(context=context)
        hp = {"http": f"http://{proxy_host}:{proxy_port}", "https": f"http://{proxy_host}:{proxy_port}"}
        proxy = urllib.request.ProxyHandler(hp)
        opener = urllib.request.build_opener(proxy, https_handler)
        urllib.request.install_opener(opener)

        # 从YouTube下载视频
        video = YouTube(video_url)
        stream = video.streams.get_highest_resolution()
        stream.download(self.down_dir_Edit.text())

        # 更新界面显示下载信息和进度
        self.down_Button.setText('正在下载')
        self.down_Button.setEnabled(False)
        self.process_label.setText(video.title)
        self.progress_bar.setMaximum(stream.filesize)
        stream.on_progress(lambda chunk: self.update_progress(chunk))

    def update_progress(self, chunk):
        # 更新下载进度
        self.progress_bar.setValue(self.progress_bar.value() + len(chunk))
        if self.progress_bar.value() == 100:
            self.down_Button.setText('下载')
            self.down_Button.setEnabled(True)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = YouTuBeMainWindow()
    window.show()
    sys.exit(app.exec_())
